package com.aydx.minirpc.core.proxy;

import com.aydx.minirpc.core.MiniRpcContext;
import com.aydx.minirpc.core.RemoteCallPackage;
import com.aydx.minirpc.core.RpcMethod;
import com.aydx.minirpc.core.common.ClassUtils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * jdk proxy 代理方法拦截器
 */
public class JdkProxyMethodHandler extends ProxyMethodHandler implements InvocationHandler {

    public JdkProxyMethodHandler(Class<?> interfaceClass, MiniRpcContext miniRpcContext) {
        super(interfaceClass, miniRpcContext);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if(!method.getDeclaringClass().equals(getInterfaceClass())){
            return method.invoke(proxy,args);
        }else {
            //获取注解参数值
            RemoteCall annotation=method.getDeclaringClass().getAnnotation(RemoteCall.class);
            String registeName=annotation.registerName();
            String group=annotation.group();
            String version=annotation.version();

            //构建远程访问包
            RemoteCallPackage remoteCallPackage=new RemoteCallPackage();
            remoteCallPackage.setInterfaceName(method.getDeclaringClass().getName());
            //
            remoteCallPackage.setArgs(args);
            RpcMethod method1=new RpcMethod().setMethod(method.getName());
            if(method.getReturnType()!=null){
                method1.setReturnTypeName(method.getReturnType().getTypeName());
            }
            method1.setArgsClassName(ClassUtils.getNames(method.getParameterTypes()));
            remoteCallPackage.setMethod(method1);
            //
            remoteCallPackage.setGroup(group);
            remoteCallPackage.setVersion(version);
            return getMiniRpcContext().getRemoteCallCenter().call(remoteCallPackage,method.getReturnType());
        }
    }
}
